package com.myNovel.novel.manager;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.myNovel.novel.core.common.constant.CacheConstants;
import com.myNovel.novel.core.common.constant.ErrorCodeEnum;
import com.myNovel.novel.dao.entity.BookInfo;
import com.myNovel.novel.dao.entity.HomeBook;
import com.myNovel.novel.dao.mapper.BookInfoMapper;
import com.myNovel.novel.dao.mapper.HomeBookMapper;
import com.myNovel.novel.dto.resp.HomeBookRespDto;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toList;

/**
 * @Author：Guxx
 * @Package：com.myNovel.novel.manager
 * @Date：2024/3/29 16:49
 * @Filename：HomeBookCacheManager
 */
@Component
@RequiredArgsConstructor
public class HomeBookCacheManager {
    private final HomeBookMapper homeBookMapper;
    private final BookInfoMapper bookInfoMapper;

    //查询首页小说推荐，并放入缓存中
    @Cacheable(cacheManager = CacheConstants.CAFFEINE_CACHE_MANAGER,
        value = CacheConstants.HOME_BOOK_CACHE_NAME)
    public List<HomeBookRespDto> listHomeBooks(){
        //首页小说从推荐表中查询需要推荐的小说
        List<HomeBook> homeBooks = homeBookMapper.selectList(null);

        //获取推荐小说的id列表
        if(!(CollectionUtils.isEmpty(homeBooks))){
            // 通过stream.map查找id，并且放到list中--stream.map,toList()，用于list中查找数据
            List<Long> bookIds = homeBooks.stream()
                    .map(HomeBook::getBookId)
                    .toList();
            QueryWrapper<BookInfo> bookInfoQueryWrapper = new QueryWrapper<>();
            bookInfoQueryWrapper.in("id",bookIds);
            List<BookInfo> bookInfos = bookInfoMapper.selectList(bookInfoQueryWrapper);

            //组装HomeBookRespDto，列表数据返回
            if (!CollectionUtils.isEmpty(bookInfos)){
                Map<Long, BookInfo> bookInfoMap = bookInfos.stream()
                        .collect(Collectors.toMap(BookInfo::getId, Function.identity()));
                return homeBooks.stream().map(v ->{
                    BookInfo bookInfo = bookInfoMap.get(v.getBookId());
                    HomeBookRespDto bookRespDto = new HomeBookRespDto();
                    bookRespDto.setBookId(v.getBookId());
                    bookRespDto.setBookName(bookInfo.getBookName());
                    bookRespDto.setPicUrl(bookInfo.getPicUrl());
                    bookRespDto.setAuthorName(bookInfo.getAuthorName());
                    bookRespDto.setBookDesc(bookInfo.getBookDesc());
                    return bookRespDto;
                }).toList();
            }
        }
        return Collections.emptyList();//返回一个空列表，且不可变。避免用null创建空列表导致空指针异常。
    }
}
